<template>
  <div>
    <div class="input-section">
      <div class="right">
        <el-input
          v-model="searchQuery"
          placeholder="请输入用户名"
          style="
            width: 500px;
            height: 40px;
            margin-bottom: 20px;
            margin-top: 20px;
          "
          :prefix-icon="Search"
          clearable
        />
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </div>
      <div class="button-group">
        <el-button @click="exportToExcel" type="success">导出 Excel</el-button>
        <el-button type="primary" @click="handleAdd">新增</el-button>
        <el-button
          type="danger"
          @click="handleBatchDelete"
          :disabled="selectedRows.length === 0"
          >批量删除</el-button
        >
      </div>
    </div>
    <el-table
      ref="tableRef"
      :data="tableData"
      style="width: 100%"
      row-key="id"
      height="500"
      :row-style="{ height: '50px' }"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50" />
      <el-table-column prop="id" label="用户ID" width="100" />
      <el-table-column prop="userAccount" label="用户账号" width="150" />
      <el-table-column prop="userName" label="用户名" width="150" />
      <el-table-column prop="phoneNumber" label="电话号码" width="200" />
      <el-table-column prop="major" label="专业" width="150" />
      <el-table-column
        prop="identity"
        label="成员身份"
        width="120"
        :filters="identityFilters"
        :filter-method="filterIdentity"
        filter-placement="bottom-end"
        :filter-multiple="true"
      >
        <template #default="{ row }">
          <el-tag type="success" v-if="row.userRole === 'user'"
            >普通成员</el-tag
          >
          <el-tag type="warning" v-else-if="row.userRole === 'manager'"
            >管理员</el-tag
          >
          <el-tag type="danger" v-else-if="row.userRole === 'president'"
            >社长</el-tag
          >
          <el-tag type="info" v-else>未知身份</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="isDelete"
        label="是否删除"
        width="100"
        :filters="deleteFilters"
        :filter-method="filterResult"
        filter-placement="bottom-end"
      >
        <template #default="{ row }">
          <el-tag v-if="row.isDelete === 0" type="success">正常</el-tag>
          <el-tag v-else-if="row.isDelete === 1" type="warning">已删除</el-tag>
          <el-tag v-else type="danger">未知类型</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button size="small" @click="handleView(row)">查看</el-button>
          <el-button size="small" type="primary" @click="handleEdit(row)"
            >编辑</el-button
          >
          <el-button size="small" type="danger" @click="handleDelete(row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-section">
      <span class="record-count">共查询到 {{ total }} 条记录</span>
      <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        v-model:page-size="pageSize"
        v-model:current-page="currentPage"
        @current-change="loadTableData"
        @size-change="loadTableData"
      />
    </div>
    <!-- 用户详细信息对话框 -->
    <el-dialog
      :title="`用户${selectedUser?.userName || ''}的详细信息`"
      v-model="dialogVisible"
      width="700px"
    >
      <el-descriptions border :column="3" direction="horizontal">
        <el-descriptions-item
          :rowspan="2"
          :width="140"
          label="用户头像"
          align="center"
        >
          <el-image
            style="width: 100px; height: 100px"
            :src="selectedUser?.userAvatar || defaultAvatar"
            :preview-src-list="[selectedUser?.userAvatar || defaultAvatar]"
          />
        </el-descriptions-item>
        <el-descriptions-item label="用户ID">{{
          selectedUser?.id
        }}</el-descriptions-item>
        <el-descriptions-item label="用户账号">{{
          selectedUser?.userAccount
        }}</el-descriptions-item>
        <el-descriptions-item label="用户名">{{
          selectedUser?.userName
        }}</el-descriptions-item>
        <el-descriptions-item label="电话号码">{{
          selectedUser?.phoneNumber
        }}</el-descriptions-item>
        <el-descriptions-item label="专业">{{
          selectedUser?.major
        }}</el-descriptions-item>
        <el-descriptions-item label="年级">{{
          selectedUser?.grade
        }}</el-descriptions-item>
        <el-descriptions-item label="班级">{{
          selectedUser?.userClass
        }}</el-descriptions-item>
        <el-descriptions-item label="所管理的社团id">{{
          selectedUser?.managedClubId
        }}</el-descriptions-item>
        <el-descriptions-item label="用户角色">
          <el-tag size="small" :type="getRoleTagType(selectedUser?.userRole)">
            {{ getRoleName(selectedUser?.userRole) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{
          formattedCreateTime
        }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{
          formattedUpdateTime
        }}</el-descriptions-item>
        <el-descriptions-item label="是否删除">
          <el-tag type="success" v-if="!selectedUser?.isDelete">否</el-tag>
          <el-tag type="danger" v-else>是</el-tag>
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="dialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
    <!-- 新增用户对话框 -->
    <el-dialog title="新增用户" v-model="addDialogVisible" width="600px">
      <el-form :model="addForm" label-width="120px">
        <el-form-item label="用户账号" required>
          <el-input
            v-model="addForm.userAccount"
            placeholder="请输入用户账号"
          />
        </el-form-item>
        <el-form-item label="用户名" required>
          <el-input v-model="addForm.userName" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" required>
          <el-input
            v-model="addForm.userPassword"
            type="password"
            show-password
            placeholder="请输入密码"
          />
        </el-form-item>
        <el-form-item label="确认密码" required>
          <el-input
            v-model="addForm.checkedUserPassword"
            type="password"
            show-password
            placeholder="请再次输入密码"
          />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="addForm.phoneNumber" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="专业">
          <el-input v-model="addForm.major" placeholder="请输入专业" />
        </el-form-item>
        <el-form-item label="年级">
          <el-input v-model="addForm.grade" placeholder="请输入年级" />
        </el-form-item>
        <el-form-item label="班级">
          <el-input v-model="addForm.userClass" placeholder="请输入班级" />
        </el-form-item>
        <el-form-item label="用户角色">
          <el-select v-model="addForm.userRole" placeholder="请选择用户角色">
            <el-option label="普通用户" value="user" />
            <el-option label="管理员" value="admin" />
            <el-option label="社长" value="president" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAddUser">确定</el-button>
      </template>
    </el-dialog>

    <!-- 编辑用户对话框 -->
    <el-dialog title="编辑用户信息" v-model="editDialogVisible" width="600px">
      <el-form :model="editForm" label-width="120px">
        <el-form-item label="用户头像">
          <el-upload
            action="#"
            :auto-upload="false"
            :on-change="handleAvatarChange"
            :show-file-list="false"
          >
            <el-button type="primary">选择头像</el-button>
            <template #tip>
              <div class="el-upload__tip">
                {{ avatarFile ? avatarFile.name : "未选择头像文件" }}
                <el-image
                  v-if="currentAvatar || selectedUser?.userAvatar"
                  style="width: 60px; height: 60px; margin-left: 10px"
                  :src="currentAvatar || selectedUser?.userAvatar"
                  :preview-src-list="[
                    currentAvatar || selectedUser?.userAvatar,
                  ]"
                />
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="用户ID">
          <el-input v-model="editForm.userId" disabled />
        </el-form-item>
        <el-form-item label="用户账号" required>
          <el-input v-model="editForm.userAccount" />
        </el-form-item>
        <el-form-item label="用户名" required>
          <el-input v-model="editForm.userName" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="editForm.phoneNumber" />
        </el-form-item>
        <el-form-item label="专业">
          <el-input v-model="editForm.major" />
        </el-form-item>
        <el-form-item label="年级">
          <el-input v-model="editForm.grade" />
        </el-form-item>
        <el-form-item label="班级">
          <el-input v-model="editForm.userClass" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveEdit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox, ElLoading } from "element-plus";
import { Search } from "@element-plus/icons-vue";
import {
  getUserAllAPI,
  deleteUserAPI,
  addUserAPI,
  updateUserAPI,
  uploadAvatarAPI,
  deleteuserAPI,
} from "@/apis/user";
import dayjs from "dayjs";
import * as XLSX from "xlsx";

// 导出为 Excel
const exportToExcel = () => {
  if (!tableData.value.length) {
    ElMessage.warning("没有可导出的数据");
    return;
  }
  console.log("表格数据：", tableData.value);
  // 提取你想要导出的字段
  const exportData = tableData.value.map((item) => ({
    用户ID: item.id,
    用户名: item.userName,
    用户账号: item.userAccount,
    用户密码: item.userPassword,
    用户号码: item.phoneNumber,
  }));

  const worksheet = XLSX.utils.json_to_sheet(exportData);
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, "社团信息");

  // 下载 Excel 文件
  XLSX.writeFile(
    workbook,
    `社团列表_${new Date().toISOString().slice(0, 10)}.xlsx`
  );
};

interface User {
  id: number;
  userAccount: string;
  userName: string;
  userPassword: string;
  userAvatar: string;
  phoneNumber: string;
  major: string;
  grade: string;
  userClass: string;
  managedClubId: number | null;
  userRole: string;
  createTime: string;
  updateTime: string;
  isDelete: boolean;
}

const tableRef = ref<any>();
const searchQuery = ref("");
const currentPage = ref(1);
const pageSize = ref(9);
const dialogVisible = ref(false);
const selectedUser = ref<User | null>(null);
const total = ref(0);
const addDialogVisible = ref(false);
const tableData = ref<User[]>([]);
const defaultAvatar =
  "https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png";
//加载用户数据
const loadTableData = async () => {
  try {
    const response = await getUserAllAPI(currentPage.value, pageSize.value, "");
    console.log("API Response:", response);
    if (response.code === 0 && response.data) {
      tableData.value = response.data.records;
      total.value = response.data.total;
    } else {
      tableData.value = [];
      total.value = 0;
      console.error("加载数据失败:", response.message || "返回数据格式错误");
    }
  } catch (error) {
    tableData.value = [];
    total.value = 0;
    console.error("加载数据时发生错误:", error.message || error);
  }
};

// 搜索功能
const handleSearch = async () => {
  try {
    currentPage.value = 1;
    const response = await getUserAllAPI(
      currentPage.value,
      pageSize.value,
      searchQuery.value
    );
    if (response.code === 0 && response.data) {
      tableData.value = response.data.records;
      total.value = response.data.total;
      if (tableData.value.length === 0) {
        ElMessage.info("未找到匹配结果");
      }
    } else {
      ElMessage.warning(response.message || "查询失败");
    }
  } catch (error) {
    console.error("搜索失败:", error);
    ElMessage.error("搜索失败");
  }
};
const resetSearch = async () => {
  searchQuery.value = "";
  await loadTableData();
};

const formattedCreateTime = computed(() => {
  return selectedUser.value?.createTime
    ? dayjs(selectedUser.value.createTime).format("YYYY-MM-DD HH:mm:ss")
    : "";
});

const formattedUpdateTime = computed(() => {
  return selectedUser.value?.updateTime
    ? dayjs(selectedUser.value.updateTime).format("YYYY-MM-DD HH:mm:ss")
    : "";
});

onMounted(() => {
  loadTableData(); // 加载数据
});

// 删除用户（优化版）
const handleDelete = async (row: User) => {
  try {
    if (!row?.id) {
      ElMessage.warning("未找到要删除的用户");
      return;
    }

    await ElMessageBox.confirm(`确定删除用户 ${row.userName} 吗？`, "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      distinguishCancelAndClose: true,
    });

    const loading = ElLoading.service({
      lock: true,
      text: "删除中...",
      background: "rgba(0, 0, 0, 0.7)",
    });

    // 调用删除接口（自动转为数组格式）
    const response = await deleteuserAPI(row.id);
    loading.close();

    if (response.code === 0) {
      ElMessage.success("用户删除成功");
      await loadTableData(); // 刷新用户列表
    } else {
      throw new Error(response.message || "删除失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除用户失败:", error);
      ElMessage.error(error.message || "删除用户失败");
    }
  }
};
// 批量删除（优化版）
const selectedRows = ref<User[]>([]);
const handleSelectionChange = (selection: User[]) => {
  selectedRows.value = selection;
};

const handleBatchDelete = async () => {
  try {
    if (selectedRows.value.length === 0) {
      return ElMessage.warning("请至少选择一条记录");
    }

    const userNames = selectedRows.value.map((u) => u.userName).join("、");

    await ElMessageBox.confirm(
      `确定删除选中的 ${selectedRows.value.length} 个用户吗？\n（${userNames}）`,
      "警告",
      {
        confirmButtonText: "确定删除",
        cancelButtonText: "取消",
        type: "warning",
        distinguishCancelAndClose: true,
        confirmButtonClass: "el-button--danger",
      }
    );

    const loading = ElLoading.service({
      lock: true,
      text: `正在删除 ${selectedRows.value.length} 个用户...`,
      background: "rgba(0, 0, 0, 0.7)",
    });

    // 提取用户ID数组
    const userIds = selectedRows.value.map((user) => user.id.toString());
    const response = await deleteUserAPI(userIds);
    loading.close();

    if (response.code === 0) {
      ElMessage.success(`成功删除 ${userIds.length} 个用户`);
      selectedRows.value = []; // 清空选中
      await loadTableData(); // 刷新列表
    } else {
      throw new Error(response.message || "批量删除失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("批量删除失败:", error);
      ElMessage.error(error.message || "批量删除失败");
    }
  }
};
// 新增表单数据
const addForm = ref({
  userAccount: "",
  userName: "",
  userPassword: "",
  checkedUserPassword: "",
  phoneNumber: "",
  major: "",
  grade: "",
  userClass: "",
  userRole: "user", // 默认普通用户
  userAvatar: "",
});

const getRoleName = (role: string | undefined) => {
  switch (role) {
    case "user":
      return "普通成员";
    case "manager":
      return "管理员";
    case "president":
      return "社长";
    default:
      return "未知角色";
  }
};

const getRoleTagType = (role: string | undefined) => {
  switch (role) {
    case "user":
      return "success";
    case "manager":
      return "warning";
    case "president":
      return "danger";
    default:
      return "info";
  }
};
const deleteFilters = [
  { text: "正常", value: false },
  { text: "已删除", value: true },
];

const handleView = (row: User) => {
  selectedUser.value = row;
  dialogVisible.value = true;
};

const identityFilters = [
  { text: "普通成员", value: "user" },
  { text: "管理员", value: "manager" },
  { text: "社长", value: "president" },
];
const filterResult = (value, row) => row.result === value;

const filterIdentity = (value: string, row: User) => {
  return row.userRole === value;
};

const editDialogVisible = ref(false);
// 编辑表单数据
const editForm = ref({
  id: 0,
  userAccount: "",
  userName: "",
  phoneNumber: "",
  major: "",
  grade: "",
  userClass: "",
  userAvatar: "",
});

// 打开新增对话框时重置
const handleAdd = () => {
  addForm.value = {
    userAccount: "",
    userName: "",
    userPassword: "",
    checkedUserPassword: "",
    phoneNumber: "",
    major: "",
    grade: "",
    userClass: "",
    userRole: "user",
  };
  // 新增用户不需要头像上传，移除相关逻辑
  addDialogVisible.value = true;
};

// 打开编辑对话框时初始化
const handleEdit = (row: User) => {
  editForm.value = {
    id: row.id,
    userAccount: row.userAccount,
    userName: row.userName,
    phoneNumber: row.phoneNumber,
    major: row.major,
    grade: row.grade,
    userClass: row.class,
    userAvatar: row.userAvatar,
  };
  avatarFile.value = null;
  currentAvatar.value = row.userAvatar || "";
  editDialogVisible.value = true;
};

// 头像文件引用
const avatarFile = ref<File | null>(null);
const currentAvatar = ref(""); // 当前显示的头像URL

// 处理头像选择
const handleAvatarChange = (uploadFile: { raw: File }) => {
  avatarFile.value = uploadFile.raw;
  // 创建预览URL
  currentAvatar.value = URL.createObjectURL(uploadFile.raw);
};

// 新增用户逻辑
const submitAddUser = async () => {
  try {
    // 1. 表单校验
    if (
      !addForm.value.userAccount?.trim() ||
      !addForm.value.userName?.trim() ||
      !addForm.value.userPassword?.trim() ||
      !addForm.value.checkedUserPassword?.trim()
    ) {
      ElMessage.warning("请填写完整信息");
      return;
    }

    if (addForm.value.userPassword !== addForm.value.checkedUserPassword) {
      ElMessage.warning("两次密码输入不一致");
      return;
    }

    const loading = ElLoading.service({
      lock: true,
      text: "正在提交...",
      background: "rgba(0, 0, 0, 0.7)",
    });

    // 2. 准备请求数据
    const requestData = {
      userAccount: addForm.value.userAccount.trim(),
      userName: addForm.value.userName.trim(),
      userPassword: addForm.value.userPassword,
      checkedUserPassword: addForm.value.checkedUserPassword,
      phoneNumber: addForm.value.phoneNumber?.trim() || undefined,
      major: addForm.value.major?.trim() || undefined,
      grade: addForm.value.grade?.trim() || undefined,
      userClass: addForm.value.userClass?.trim() || undefined,
      userRole: addForm.value.userRole || "user",
    };

    // 3. 新增用户
    const userRes = await addUserAPI(requestData);
    if (userRes.code !== 0) throw new Error(userRes.message || "新增失败");

    // 新增用户不再上传头像

    loading.close();
    ElMessage.success("用户创建成功");
    addDialogVisible.value = false;
    await loadTableData();
  } catch (error: any) {
    ElMessage.error(error.message || "创建用户失败");
  }
};

// 编辑用户逻辑
const saveEdit = async () => {
  try {
    // 1. 校验
    if (!editForm.value.userAccount || !editForm.value.userName) {
      ElMessage.warning("请填写用户账号和姓名");
      return;
    }

    const loading = ElLoading.service({
      lock: true,
      text: "正在保存用户信息...",
      background: "rgba(0, 0, 0, 0.7)",
    });
    // 2. 上传新头像
    let avatarUrl = editForm.value.userAvatar;
    if (avatarFile.value) {
      const uploadRes = await uploadAvatarAPI(
        avatarFile.value,
        editForm.value.id
      );
      if (uploadRes.code !== 0)
        throw new Error(uploadRes.message || "头像上传失败");
      avatarUrl = uploadRes.data;
    }

    // 3. 调用更新接口
    const userRes = await updateUserAPI({
      id: editForm.value.id,
      userAccount: editForm.value.userAccount,
      userName: editForm.value.userName,
      phoneNumber: editForm.value.phoneNumber,
      major: editForm.value.major,
      grade: editForm.value.grade,
      userClass: editForm.value.userClass,
      userAvatar: avatarUrl,
    });

    loading.close();

    if (userRes.code === 0) {
      ElMessage.success("用户信息更新成功");
      editDialogVisible.value = false;
      await loadTableData();
    } else {
      throw new Error(userRes.message);
    }
  } catch (error: any) {
    ElMessage.error(`更新失败: ${error.message}`);
  }
};
</script>

<style scoped>
.input-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.button-group {
  display: flex;
  gap: 10px;
}

.pagination-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}

.record-count {
  font-size: 14px;
  color: #666;
}

.el-table {
  margin-bottom: 20px;
}

.el-pagination {
  justify-content: center;
}
.right {
  display: flex;
  align-items: center;
  gap: 10px;
}
</style>
